package com.itany.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itany.constant.Constant;
import com.itany.pojo.User;
import com.itany.user.service.UserService;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import utils.AjaxResult;
import utils.HttpClinetUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by tyh on 2018/9/22.
 */
@Controller
@RequestMapping("/userserver")
public class UserController {

    @Reference
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;





    @RequestMapping("/sendMsg")
    @ResponseBody
    public AjaxResult sendMsg(User user){

        Random random = new Random();
        int count =6 ;
        String s="1234567890";
        StringBuffer code = new StringBuffer();
        for(int i=0;i<count;i++){
            // 随机取一个字符
            String c = new String(new char[]{s.charAt(random.nextInt(s.length()))});
            code.append(c);
        }
        Map<String,String> params = new HashMap<String,String>();
        params.put("mobile",user.getPhone());
        params.put("tpl_id","190542");
        params.put("tpl_value","%23code%23%3d"+code);
        params.put("key","68774af6529c9f513d0e84a534242332");
        params.put("dtype","json");
        HttpClinetUtils.doPost("http://v.juhe.cn/sms/send",params);
        redisTemplate.opsForValue().set("code",code.toString(),6000, TimeUnit.SECONDS);
        System.out.println(code);
        return AjaxResult.isOk(code);

    }
    @RequestMapping("/addUser")
    @ResponseBody
    public AjaxResult addUser(User user, @RequestParam("phoneCode")String phoneCode){

        String code = redisTemplate.opsForValue().get("code");

        user.setUsername(user.getPhone());
        user.setStatus(Constant.USER_ENABLE_STATUS);

        if(!phoneCode.equals(code)){
            return AjaxResult.isFail("验证码错误");
        }




        System.out.println(user);
        userService.addUser(user);
        return AjaxResult.isOk();
    }

    // @RequestMapping("/findUsers")
    // public ModelAndView findUsers(@RequestParam(defaultValue = "1")Integer pageNo,
    //                               @RequestParam(defaultValue = "10")Integer pageSize){
    //     PageInfo<User> pageInfo =  userService.findUsers(pageNo,pageSize);
    //     Map<String,Object> map = new HashMap<String,Object>();
    //     map.put("pageInfo",pageInfo);
    //     return new ModelAndView("userlist",map);
    // }


   /* @RequestMapping("/login")
    public String login(User user, HttpServletResponse response){
        User u = userService.login(user);
        u.setPassword(null);
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("USER_TOKEN::"+token, JSON.toJSONString(u),1800,TimeUnit.SECONDS);
        Cookie ck = new Cookie("TT_TOKEN",token);
        ck.setPath("/");
        response.addCookie(ck);
        return "redirect:http://localhost:9003/user/userserver/findUsers";
    }*/

    @RequestMapping("/casIndex")
   public String casIndex(HttpServletRequest request){
        Assertion assertion = (Assertion)request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        Principal principal =  assertion.getPrincipal();
        String userName = principal.getName();
        System.out.println("-------------------"+userName);
            Map<String,Object> map = ((AttributePrincipal)principal).getAttributes();
            for(Map.Entry<String,Object> entry :map.entrySet()){
                System.out.println(entry.getKey()+"---------------"+entry.getValue());
            }
        return "register";


   }

    @RequestMapping("/casLogout")
   public String casLogout(HttpSession session){
       session.invalidate();
       return "redirect:http://localhost:8443/cas/logout";
   }



}
